package com.wy.allthingdone.activity;

import android.animation.Animator;
import android.animation.ObjectAnimator;
import android.animation.PropertyValuesHolder;
import android.animation.ValueAnimator;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.wy.allthingdone.R;
import com.wy.allthingdone.adapters.ItemAdapter;
import com.wy.allthingdone.adapters.RecycleViewDivider;
import com.wy.allthingdone.views.GifView;

import org.xutils.view.annotation.ViewInject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {

    private ItemAdapter adapter;
    private ArrayList<String> mFileName;
    private ArrayList<String> mFilePath;
    public static String ROOT_PATH = "/";
    private List list;
    public ObjectAnimator anmator;
    private FloatingActionButton fab;
    private ObjectAnimator ani;
    private View view;
    private EditText editText;
    private String currentWhere = "";

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_main);
        super.onCreate(savedInstanceState);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);//设置actionbar
        setSupportActionBar(toolbar);

        gifView.setGifResource(R.drawable.sister_name, true);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(RecyclerView.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        list = showFileDir(ROOT_PATH);
        adapter = new ItemAdapter(this, list);
        adapter.setItemOnClickEvent(new ItemAdapter.ItemOnClickEvent() {
            @Override
            public void doItemClick(String where) {
                currentWhere = where;
                File file = new File(where);
                // 文件存在并可读
                if (file.exists() && file.canRead()) {
                    if (file.isDirectory()) {
                        //显示子目录及文件
                        if (showFileDir(where).size() != 0) {
                            Log.i("TAG", "file.canRead()===============" + file.canRead());
                            Log.i("TAG", "file.canRead()===============" + file.listFiles().length);
                            list.clear();
                            adapter.notifyDataSetChanged();
                            list = showFileDir(where);
                            adapter.setAdapterNoti(list);
                        } else {
                            Toast.makeText(MainActivity.this, "不能打开此文件", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        //处理文件
                        if (where.contains(".png") || where.contains(".jpg") || where.contains(".PNG") || where.contains(".JPG")) {
                            Intent intent_view = new Intent(MainActivity.this, ImageViewActivity.class);
                            intent_view.putExtra("data", where);
                            startActivity(intent_view);
                        } else if (where.contains(".mp4") || where.contains(".MP4") || where.contains(".avi") || where.contains(".AVI")) {
                            Intent intent_reader = new Intent(MainActivity.this, VideoViewActivity.class);
                            intent_reader.putExtra("data", where);
                            startActivity(intent_reader);
                        } else if (where.contains(".txt") || where.contains(".TXT") || where.contains(".log") || where.contains(".LOG")) {
//                            Intent intent_reader = new Intent(MainActivity.this, TextReaderActivity.class);
//                            intent_reader.putExtra("data", where);
//                            startActivity(intent_reader);
                            Intent intent = new Intent();
                            intent.putExtra("bookname", where.substring(where.lastIndexOf("/") + 1));
                            intent.putExtra("bookpath", where);
                            intent.setClass(MainActivity.this, HwReaderPlayActivity.class);
                            MainActivity.this.startActivity(intent);
                        } else if (where.contains(".mp3") || where.contains(".MP3") || where.contains(".amr") || where.contains(".AMR")) {
                            Intent intent_reader = new Intent(MainActivity.this, MusicPlayActivity.class);
                            intent_reader.putExtra("data", where);
                            startActivity(intent_reader);
                        } else if (where.contains(".apk") || where.contains(".APK")) {
                            Toast.makeText(MainActivity.this, "安装程序!", Toast.LENGTH_SHORT).show();
//                            Intent intent = new Intent(Intent.ACTION_VIEW);
//                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            //filePath为文件路径
//                            intent.setDataAndType(Uri.fromFile(new File(where)), "application/vnd.android.packagearchive");
//                            startActivity(intent);
                        } else {
                            fileHandle(file);
                        }
                    }
                }
                //没有权限
                else {
                    Resources res = getResources();
                    new AlertDialog.Builder(MainActivity.this).setTitle("Message")
                            .setMessage("没有权限")
                            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    Toast.makeText(getApplicationContext(), "权限不够了哟!", Toast.LENGTH_SHORT).show();
                                }
                            }).show();
                }
            }
        });
        recyclerView.setAdapter(adapter);
        //设置Item增加、移除动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        Log.i("TAG", "recyclerView====" + recyclerView);
        fab = (FloatingActionButton) findViewById(R.id.float_button);
        fab.setOnClickListener(new View.OnClickListener() {


            @Override
            public void onClick(final View v) {
                v.setTag("click");
                if (anmator == null) {
                    anmator = ObjectAnimator
//                            .ofFloat(v, "rotationY", 360.0F, 0.0F)
                            .ofFloat(v, "zhy", 1.0F, 0.0F)//
                            .setDuration(500);
                    anmator.addListener(new Animator.AnimatorListener() {
                        @Override
                        public void onAnimationStart(Animator animation) {

                        }

                        @Override
                        public void onAnimationEnd(Animator animation) {
                            if (v.getTag().toString().equals("click")) {
//                                startActivity(new Intent(MainActivity.this, TabEchartsActivity.class));
                                startActivity(new Intent(MainActivity.this, PreViewActivity.class));
                            }
                        }

                        @Override
                        public void onAnimationCancel(Animator animation) {

                        }

                        @Override
                        public void onAnimationRepeat(Animator animation) {

                        }
                    });
                    anmator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float cVal = (Float) animation.getAnimatedValue();
//                            Log.i("TAG", "cVal=======" + cVal);
                            if (v.getTag().equals("click")) {
                                v.setAlpha(cVal);
                                v.setScaleX(cVal);
                                v.setScaleY(cVal);
                            } else {
                                v.setAlpha(1.0f);
                                v.setScaleX(1.0f);
                                v.setScaleY(1.0f);
                            }
                        }
                    });
                }
                anmator.start();

            }
        });
        PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0f, 1f);
        PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f, 0, 1f);
        PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f, 0, 1f);
        ani = ObjectAnimator.ofPropertyValuesHolder(gifView, pvhX, pvhY, pvhZ).setDuration(1000);
        recyclerView.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL));
        recyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        // 触摸按下时的操作
                        adapter.setStopPlay(true);
                        adapter.notifyDataSetChanged();
                        ani.start();
                        Log.i("TAG", "开始滑动-=========");
                        break;
                    case MotionEvent.ACTION_MOVE:
                        Log.i("TAG", "滑动-=========");
                        break;
                    case MotionEvent.ACTION_UP:
                        // 触摸抬起时的操作
                        adapter.setStopPlay(false);
                        adapter.notifyDataSetChanged();
                        Log.i("TAG", "停止滑动-=========");
                        break;
                }
                return false;
            }
        });
    }

    @ViewInject(R.id.gifView)
    GifView gifView;
    @ViewInject(R.id.recycleView)
    RecyclerView recyclerView;

    /**
     * 扫描显示文件列表
     *
     * @param path
     */
    private List showFileDir(String path) {
        mFileName = new ArrayList<String>();
        mFilePath = new ArrayList<String>();
        File file = new File(path);

        File[] files = file.listFiles();
        //如果当前目录不是根目录
        if (!ROOT_PATH.equals(path)) {
            mFileName.add("@1");
            mFilePath.add(ROOT_PATH);
            mFileName.add("@2");
            mFilePath.add(file.getParent());
        }
        List<String> list = new ArrayList<String>();
        Log.i("TAG", "files==========" + files.length);
        //添加所有文件
        for (File f : files) {
            mFileName.add(f.getName());
            mFilePath.add(f.getPath());
            list.add(f.getPath());
//            list.add("/charger");
        }
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (anmator != null) {
            fab.setTag("");
            anmator.ofFloat(fab, "dsa", 0.0F, 1.0F);
            anmator.start();
        }
    }

    //对文件进行增删改
    private void fileHandle(final File file) {
        DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 打开文件
                if (which == 0) {
                    openFile(file);
                }
                //修改文件名
                else if (which == 1) {
                    LayoutInflater factory = LayoutInflater.from(MainActivity.this);
                    view = factory.inflate(R.layout.rename_dialog, null);
                    editText = (EditText) view.findViewById(R.id.editText);
                    editText.setText(file.getName());

                    DialogInterface.OnClickListener listener2 = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                            String modifyName = editText.getText().toString();
                            final String fpath = file.getParentFile().getPath();
                            final File newFile = new File(fpath + "/" + modifyName);
                            if (newFile.exists()) {
                                //排除没有修改情况
                                if (!modifyName.equals(file.getName())) {
                                    new AlertDialog.Builder(MainActivity.this)
                                            .setTitle("注意!")
                                            .setMessage("文件名已存在，是否覆盖？")
                                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    if (file.renameTo(newFile)) {
                                                        showFileDir(fpath);
                                                        displayToast("重命名成功！");
                                                    } else {
                                                        displayToast("重命名失败！");
                                                    }
                                                }
                                            })
                                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {

                                                }
                                            })
                                            .show();
                                }
                            } else {
                                if (file.renameTo(newFile)) {
                                    showFileDir(fpath);
                                    displayToast("重命名成功！");
                                } else {
                                    displayToast("重命名失败！");
                                }
                            }
                        }
                    };
                    AlertDialog renameDialog = new AlertDialog.Builder(MainActivity.this).create();
                    renameDialog.setView(view);
                    renameDialog.setButton("确定", listener2);
                    renameDialog.setButton2("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            // TODO Auto-generated method stub
                        }
                    });
                    renameDialog.show();
                }
                //删除文件
                else {
                    new AlertDialog.Builder(MainActivity.this)
                            .setTitle("注意!")
                            .setMessage("确定要删除此文件吗？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (file.delete()) {
                                        //更新文件列表
                                        showFileDir(file.getParent());
                                        displayToast("删除成功！");
                                    } else {
                                        displayToast("删除失败！");
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                }
                            }).show();
                }
            }
        };
        //选择文件时，弹出增删该操作选项对话框
        String[] menu = {"打开文件", "重命名", "删除文件"};
        new AlertDialog.Builder(MainActivity.this)
                .setTitle("请选择要进行的操作!")
                .setItems(menu, listener)
                .setPositiveButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
    }

    //打开文件
    private void openFile(File file) {
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(android.content.Intent.ACTION_VIEW);
        String type = getMIMEType(file);
        intent.setDataAndType(Uri.fromFile(file), type);
        startActivity(intent);
    }

    //获取文件mimetype
    private String getMIMEType(File file) {
        String type = "";
        String name = file.getName();
        //文件扩展名
        String end = name.substring(name.lastIndexOf(".") + 1, name.length()).toLowerCase();
        if (end.equals("m4a") || end.equals("mp3") || end.equals("wav")) {
            type = "audio";
        } else if (end.equals("mp4") || end.equals("3gp")) {
            type = "video";
        } else if (end.equals("jpg") || end.equals("png") || end.equals("jpeg") || end.equals("bmp") || end.equals("gif")) {
            type = "image";
        } else {
            //如果无法直接打开，跳出列表由用户选择
            type = "*";
        }
        type += "/*";
        return type;
    }

    private void displayToast(String message) {
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onBackPressed() {
        if (currentWhere.split("/").length >= 2) {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < currentWhere.split("/").length; i++) {
                if (i != currentWhere.split("/").length - 1) {
                    sb.append("/" + currentWhere.split("/")[i]);
                }
            }
            Log.i("TAG", "sb=======" + sb.toString());
            list.clear();
            adapter.notifyDataSetChanged();
            list = showFileDir(sb.toString());
            adapter.setAdapterNoti(list);
            currentWhere = sb.toString();
        } else {
            Toast.makeText(MainActivity.this, "再点击就退出leyo", Toast.LENGTH_SHORT).show();
        }

    }
}
